package com.gec.system.service.impl;

import com.gec.model.entity.SysEstateCount;
import com.gec.system.custom.CustomUser;
import com.gec.system.service.SysEstateCountService;
import com.gec.system.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private SysEstateCountService sysEstateCountService;

    @Autowired
    private SysMenuService sysMenuService;


    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {


        //根据登录名查询账号
        SysEstateCount sysEstateCount = this.sysEstateCountService.getCountInfoUserName(loginName);
        //判断是否为空
        if (null==sysEstateCount){
            throw new UsernameNotFoundException("用户名不存在！");
        }

        //todo
//        if(sysEstateCount.getStatus().intValue() == 0) {
//            throw new RuntimeException("账号已停用");
//        }

//        return new CustomUser(sysEstateCount, Collections.emptyList());


        List<String> countPermsList = sysMenuService.findCountPermsList(sysEstateCount.getId());
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();

        for (String perm : countPermsList) {
            authorities.add(new SimpleGrantedAuthority(perm.trim()));
        }
        return new CustomUser(sysEstateCount, authorities);

    }
}
